<template>
  <div class="sorder-container" ref="sOrderContainerRef">
    <table-index :table="table" class="custom-table" @loadData="loadData">
      <template #table-summary>
        <a-alert v-if="isCreate"> 先新增车型价格模版，保存后再配置价格 </a-alert>
        <div class="table-summary-wrapper" v-else>
          <!-- 查询 -->
          <modelFilter :modelList="carPriceModelList" :siteList="siteList" @search="onFilterSearch" />
          <div class="car-model-summary">
            <div class="car-model-summary-item">
              车型数量：<span class="car-model-summary-value">{{ carModelSummaryTotalModelNum }} </span>
            </div>
            <!-- <div class="spliter"></div>
            <div class="car-model-summary-item">
              未配置车型数量：<span class="car-model-summary-value">{{ carModelSummaryNoModelNum }} </span>
            </div> -->
          </div>
        </div>
      </template>
      <template #table-header-after v-if="!isCreate">
        <a-alert style="margin-top: 16px; align-items: flex-start">
          <p style="color: #ff4e4eff">设置车型价格前，请一定先匹配好门店及车型，未准确设定将影响反写结果，导致反写失败。</p>
          <p>点击【批量设置价格】时，系统将默认保存列表中车型现有价格</p>
        </a-alert>
      </template>
      <template #modelName="{ record }">
        <div class="model-name">{{ record.modelName }}</div>
        <div class="" v-if="!record.id && !isCreate" style="margin-top: 8px; color: #f53f3fff">
          <icon-exclamation-circle-fill style="color: #f53f3fff; margin-right: 2px" />需保存后生效
        </div>
      </template>
      <template #siteNameList="{ record }">
        <template v-if="record.siteNameList && record.siteNameList.length > 0">
          <more-popup :list="record.siteNameList" />
        </template>
      </template>
      <template #channelList="{ record }">
        <div class="channel-list" v-if="record.channelList?.length > 0">
          <div class="channel-item" v-for="(item, index) in record.channelList" :key="index">
            <div class="channel-item-account">{{ `${item.sourceIdName}-${item.username}` }}</div>
            <div class="channel-item-status" :class="[item.status == 1 ? 'success' : '']">{{ item.statusName }}</div>
          </div>
        </div>
      </template>
      <!-- 平日价 -->
      <template #price="{ record, rowIndex }">
        <priceForm :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="price" />
      </template>
      <!-- 周末价 -->
      <template #weekPriceTitle>
        <div class="week-price-title">
          周末价
          <span>反写时周末价及时间必须填写，且金额需>0，未填写时则反写失败</span>
        </div>
      </template>
      <template #weekendPrice="{ record, rowIndex }">
        <priceForm class="weekend-price-form" :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="weekendPrice" />
      </template>
      <!-- 手续费 -->
      <template #poundageAmount="{ record, rowIndex }">
        <priceForm :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="poundageAmount" />
      </template>
      <!-- 基础保险 -->
      <template #insuranceAmount="{ record, rowIndex }">
        <priceForm :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="insuranceAmount" />
      </template>
      <!-- 租车押金 -->
      <template #carDeposit="{ record, rowIndex }">
        <priceForm :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="carDeposit" />
      </template>
      <!-- 违章押金 -->
      <template #illegalDeposit="{ record, rowIndex }">
        <priceForm :record="record" :fieldPrefix="`tenantPriceModelList.${rowIndex}`" priceType="illegalDeposit" />
      </template>
    </table-index>

    <!-- 价格日历 -->
    <price-calendar-modal ref="priceCalendarModalRef" />
    <!-- 节假日配置 -->
    <holiday-config-modal ref="holidayConfigModalRef" />
    <!-- 批量设置价格 -->
    <batch-price-setting-modal ref="batchPriceSettingModalRef" @success="handleBatchPriceSettingSuccess" />
  </div>
</template>

<script setup name="CarModelPriceFormSorder">
  import { ref, reactive, inject, computed } from 'vue'
  import { isValid } from '@/utils'
  import { getPriceCalendar, getTemplateDetail, editTemplate } from '@/api/business/price.js'
  import { Modal } from '@arco-design/web-vue'
  import modelFilter from './sorder-config/model-filter.vue'
  // 价格日期 & 节假日配置
  import priceCalendarModal from './price-calendar-modal.vue'
  import holidayConfigModal from './holiday-config/holiday-config-modal.vue'
  // 批量设置价格
  import batchPriceSettingModal from './sorder-config/batch-price-setting-modal.vue'
  // 价格设置
  import priceForm from './sorder-config/price-form.vue'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  // 是否是新增页面
  const isCreate = route.name == 'CarModelPriceForm_Create'
  import { useTable } from '@/hooks/table'

  const emits = defineEmits(['batchPriceSettingSuccess'])
  const form = inject('form')
  const formRef = inject('formRef')
  const batchPriceSettingModalRef = ref(null)

  // 车型数量
  const carModelSummaryTotalModelNum = computed(() => {
    return form.tenantPriceModelList?.length || 0
  })
  // 未配置车型数量
  const carModelSummaryNoModelNum = computed(() => {
    let dataList = form.tenantPriceModelList || []
    return dataList.filter((item) => {
      return !isValid(item.price)
    }).length
  })

  // 车型列表
  const carPriceModelList = computed(() => {
    return form.tenantPriceModelList.map((item) => {
      return {
        // 此处取 车型价格Id, 而非车型id
        value: item.id,
        label: item.modelName,
      }
    })
  })

  // 门店列表
  const siteList = computed(() => {
    const list = []
    form.tenantPriceModelList.forEach((item) => {
      const siteNameList = item.siteNameList || []
      list.push(...siteNameList)
    })
    const uniqueArray = [...new Set(list)]
    return uniqueArray
  })

  // 节假日配置弹窗
  const holidayConfigModalRef = ref()
  // 节假日点击事件
  const handleCarModelHolidayFn = (record) => {
    askForConfirmFn(record.id, () => {
      // 当前车型的主键 id
      const newRecord = table.dataList.find((item) => {
        return item.modelId == record.modelId
      })
      holidayConfigModalRef.value.open(newRecord)
    })
  }
  // 询问处理函数
  const askForConfirmFn = (condition, callback) => {
    // 如果传入的 condition 为 true，则直接执行回调函数
    if (condition) {
      callback()
    } else {
      // 保存模板，获取最新的模板 id
      Modal.confirm({
        title: '提示',
        simple: true,
        cancelText: '关闭',
        okText: '确认',
        content: '点击此操作，系统将保存当前模板，请确认是否继续操作？',
        onOk: () => {
          // 触发保存操作
          saveAndUpdateFn().then(() => {
            callback()
          })
        },
      })
    }
  }
  /** 保存并更新列表
   * @param {Boolean} isUpdate 是否更新列表
   */
  const saveAndUpdateFn = (isUpdate = true) => {
    return new Promise((resolve, reject) => {
      // 触发保存操作
      formRef.value.validate((error) => {
        if (!error) {
          // 保存模板
          editTemplate(form)
            .then(() => {
              if (isUpdate) {
                // 获取最新的模板数据
                getTemplateDetail({ id: form.id })
                  .then((res) => {
                    const result = res.result
                    // 更新车型数据
                    updateTableList(result.tenantPriceModelList)
                    resolve()
                  })
                  .catch(() => {
                    reject()
                  })
              } else {
                resolve()
              }
            })
            .catch(() => {
              reject()
            })
        } else {
          reject()
        }
      })
    })
  }
  // 批量设置价格
  const batchPriceSettingFn = () => {
    // 保存车型价格
    saveAndUpdateFn().then(() => {
      const tenantPriceModelList = form.tenantPriceModelList
      if (tenantPriceModelList?.length > 0) {
        // 渠道信息
        let channelInfo = null
        let firstTenanPriceModel = tenantPriceModelList[0]
        if (firstTenanPriceModel.channelPriceList) {
          const channelPriceList = firstTenanPriceModel.channelPriceList
          channelInfo = channelPriceList.map((item) => {
            return {
              sourceId: item.sourceId,
              sourceIdName: item.sourceIdName,
            }
          })
        }
        batchPriceSettingModalRef.value.open(form.id, carPriceModelList.value, channelInfo)
      }
    })
  }
  // 价格日历点击事件
  const priceCalendarModalRef = ref()
  // table 配置
  const tablePagination = reactive({
    page: 1,
    pageSize: 10,
    pageCount: 1,
  })
  const table = useTable({
    pagination: tablePagination,
    tableLoading: false,
    columns: isCreate
      ? [
          { title: '车型', dataIndex: 'modelName', slotName: 'modelName' },
          { title: '车辆数量', dataIndex: 'carNumber' },
          { title: '应用门店', dataIndex: 'siteNameList', slotName: 'siteNameList' },
        ]
      : [
          { title: '车型', width: 160, dataIndex: 'modelName', slotName: 'modelName' },
          { title: '车辆数量', width: 120, dataIndex: 'carNumber' },
          { title: '应用门店', width: 180, dataIndex: 'siteNameList', slotName: 'siteNameList' },
          { title: '是否匹配OTA车型', width: 160, dataIndex: 'channelList', slotName: 'channelList' },
          { title: '平日价', width: 184, dataIndex: 'price', slotName: 'price' },
          { title: '周末价', width: 440, dataIndex: 'weekendPrice', titleSlotName: 'weekPriceTitle', slotName: 'weekendPrice' },
          { title: '手续费', width: 184, dataIndex: 'poundageAmount', slotName: 'poundageAmount' },
          { title: '基础保险', width: 180, dataIndex: 'insuranceAmount', slotName: 'insuranceAmount' },
          { title: '租车押金', width: 180, dataIndex: 'carDeposit', slotName: 'carDeposit' },
          { title: '违章押金', width: 180, dataIndex: 'illegalDeposit', slotName: 'illegalDeposit' },
        ],
    operates: isCreate
      ? undefined
      : [
          {
            label: '自定义及节假日',
            method: (record) => {
              handleCarModelHolidayFn(record)
            },
          },
          {
            label: '价格日历',
            method: (record) => {
              priceCalendarModalRef.value.open(record.modelName)
              // 获取价格日历信息
              const param = {
                priceModelId: record.id,
                price: record.price,
                weekendPrice: record.weekendPrice,
                weekendDayList: record.weekendDayList,
              }
              getPriceCalendar(param).then((res) => {
                const result = res.result
                priceCalendarModalRef.value.setPriceList(result)
              })
            },
          },
        ],
    buttons: [
      {
        label: '批量设置价格',
        // 新增车型价格模板不支持 批量设置价格
        show: !isCreate,
        type: 'primary',
        method: batchPriceSettingFn,
      },
    ],
    operateColumnWidth: 130,
  })

  /**
   * 更新 tableList
   * @param {Array} list 更新的列表数据
   * @param {Boolean} operateType 操作类型，getDetail | siteChoice(选择门店)
   */
  const updateTableList = (list, operateType) => {
    // 当前车型列表
    const tenantPriceModelList = form.tenantPriceModelList || []
    // 对接口返回的结果进行处理
    for (let i = 0; i < list.length; i++) {
      let item = list[i]
      // 详情操作，仅处理部分默认值
      if (operateType == 'siteChoice') {
        // 如果当前车型已经存在，则将当前录入信息合并到 list>item 中，保证录入信息一直存在
        let currItem = tenantPriceModelList.find((nowDataItem) => nowDataItem.modelId == item.modelId)
        if (currItem) {
          // 将当前录入的车型价格回填
          Object.assign(item, {
            ...currItem,
            id: item.id,
          })
        } else {
          item.price = item.price ?? 0
          item.poundageAmount = item.poundageAmount ?? 0
          item.insuranceAmount = item.insuranceAmount ?? 0
          item.carDeposit = item.carDeposit ?? 0
          item.illegalDeposit = item.illegalDeposit ?? 0

          // 此时周末设置 默认五六日
          item.weekendDayList = [5, 6, 7]
          // 处理渠道周末设置 默认五六日
          item.channelPriceList.forEach((channelItem) => {
            channelItem.weekendDayList = [5, 6, 7]
          })
        }
      }
    }

    // 更新 form.tenantPriceModelList
    form.tenantPriceModelList = list
    // 加载数据
    loadData(1)
  }
  // 分割一维数组为二维数组
  const splitArray2Array = (list) => {
    // 前端分页数据维护
    const pageSize = tablePagination.pageSize
    const tempList = [...list]
    tablePagination.pageCount = tempList.length
    const result = [[]]
    while (tempList.length > 0) {
      let last = result[result.length - 1]
      if (last.length >= pageSize) {
        result.push([])
        last = result[result.length - 1]
      }
      last.push(tempList[0])
      tempList.splice(0, 1)
    }
    return result
  }
  // 查询搜索
  const onFilterSearch = (param) => {
    loadData(1, param)
  }
  const sOrderContainerRef = ref(null)
  // 加载数据
  const loadData = (pageNumber, param) => {
    if (pageNumber) tablePagination.page = pageNumber
    if (param && (param.modelKeyword || param.siteKeyword)) {
      const tenantPriceModelList = form.tenantPriceModelList
      const tempList = splitArray2Array(
        tenantPriceModelList.filter((item) => {
          let show = true
          // 过滤 modelKeyword
          if (param.modelKeyword) {
            const modelName = (item.modelName ?? '').toLowerCase()
            if (modelName) {
              show = modelName.includes(param.modelKeyword.toLowerCase())
            } else {
              show = false
            }
          }
          // 如果在过滤了车型名称后，依旧显示，此时过滤门店名称
          if (show && param.siteKeyword) {
            const siteNameList = item.siteNameList
            if (siteNameList.length > 0) {
              show = siteNameList.some((siteItem) => {
                return siteItem.includes(param.siteKeyword.toLowerCase())
              })
            } else {
              show = false
            }
          }
          return show
        })
      )
      table.dataList = tempList[tablePagination.page - 1]
    } else {
      const tempList = splitArray2Array(form.tenantPriceModelList)
      table.dataList = tempList[tablePagination.page - 1]
    }

    // 表格滚动到顶部
    const $body = sOrderContainerRef.value.querySelector('.arco-table-body')
    $body.scrollTo(0, 0)
  }

  const handleBatchPriceSettingSuccess = () => {
    emits('batchPriceSettingSuccess')
  }

  defineExpose({
    updateTableList,
  })
</script>

<style lang="less" scoped>
  .sorder-container {
    :deep(#tableHeaderContainer) {
      .arco-card-body {
        padding-bottom: 16px !important;
      }
    }
  }
  .custom-listsearcher {
    :deep(.form-item-label) {
      width: 86px !important;
    }
  }
  .weekend-price-form {
    :deep(.custom-input-number) {
      width: 210px !important;
    }
  }
  .table-summary-wrapper {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .car-model-summary {
      color: #4e5969;
      padding-top: 4px;
      display: flex;
      flex-shrink: 0;
      align-items: center;
      margin-right: 20px;
      .car-model-summary-item {
        display: inline-block;
      }
      .spliter {
        width: 1px;
        height: 12px;
        background: #1d2129;
        border-radius: 0px 0px 0px 0px;
        margin: 0 16px;
      }
      .car-model-summary-value {
        color: #1890ff;
      }
    }
  }

  .channel-list {
    .channel-item {
      font-size: 14px;
      color: #1d2129;
      line-height: 20px;
      .channel-item-status {
        color: #f53f3f;
        &.success {
          color: #00b42a;
        }
      }
    }
    .channel-item + .channel-item {
      margin-top: 12px;
    }
  }
  .custom-table {
    :deep(.arco-table-col-fixed-right) {
      .arco-table-cell {
        padding: 9px 12px;
      }
    }
    :deep(.operate-button) {
      width: 100% !important;
      justify-content: center;
    }
  }
  .custom-form-item {
    :deep(.arco-form-item) {
      margin-bottom: 12px;
    }
  }
  .one-write {
    padding: 0;
  }
  .week-price-title {
    span {
      font-weight: 400;
      font-size: 12px;
      color: #f53f3f;
      margin-left: 8px;
    }
  }
</style>
